﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ISIM
{
    public partial class ChatForm : Form
    {
        private FormWindowState lastState;

        public ChatForm(ISIMContact contact)
        {
            InitializeComponent();

            lastState = WindowState;
            this.TopMost = Global.OpenForms.mainForm.TopMost;
            chatTabs.AddTab(contact, true);
            chatTabs.ChatTabs_Resize(null, null);
            this.Text = Global.Converter.GetRenamedContactName(contact);
        }

        /// <summary>
        /// Čekování stisknutých kláves, změna aktivního tabu
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.Shift | Keys.Tab))
            {
                if (chatTabs.SelectedIndex > 0)
                    chatTabs.SelectedIndex--;
                else
                    chatTabs.SelectedIndex = chatTabs.TabPages.Count - 1;
                return true;
            }
            else if (keyData == (Keys.Control | Keys.Tab))
            {
                foreach (ChatTabPage page in chatTabs.TabPages)
                {
                    if ((page.contact != null) && (page.contact.unreadedMessage == true))
                    {
                        chatTabs.SelectedTab = page;
                        return true;
                    }
                }

                if (chatTabs.SelectedIndex < chatTabs.TabPages.Count - 1)
                    chatTabs.SelectedIndex++;
                else
                    chatTabs.SelectedIndex = 0;
                return true;
            }

            if ((keyData == Keys.Escape) || (keyData == (Keys.Control | Keys.W)))
                CloseTab(chatTabs.SelectedTab as ChatTabPage);

            return base.ProcessCmdKey(ref msg, keyData);
        }

        public bool CloseTab(ChatTabPage tabPage)
        {
            if (tabPage.contact.unreadedMessage)
            {
                if (MessageBox.Show(Global.LangManager.Translate("unreadedMessage") + " " + Global.LangManager.Translate("from") + " " + Global.Converter.GetRenamedContactName(tabPage.contact) + ".\n" + Global.LangManager.Translate("close") + "?", Global.LangManager.Translate("unreadedMessage"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return false;
                }
            }

            chatTabs.RemoveTab(tabPage);
            GC.Collect();

            if (chatTabs.TabCount == 0)
                this.Close();

            return true;
        }

        private void ChatForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Global.OpenForms.chatForm = null;
        }

        private void chatTabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chatTabs.SelectedTab == null)
                return;
            
            if ((chatTabs.SelectedTab as ChatTabPage).contact.unreadedMessage)
            {
                (chatTabs.SelectedTab as ChatTabPage).contact.unreadedMessage = false;

                Global.OpenForms.mainForm.Invoke(new MethodInvoker(() => { Global.OpenForms.mainForm.Refresh(); }));
                chatTabs.Refresh();
            }

            chatTabs.ChatTabs_Resize(null, null);
            (chatTabs.SelectedTab as ChatTabPage).msgTb.Focus();

            this.Text = Global.Converter.GetRenamedContactName((chatTabs.SelectedTab as ChatTabPage).contact);
        }

        private void ChatForm_Shown(object sender, EventArgs e)
        {
            (chatTabs.SelectedTab as ChatTabPage).msgTb.Focus();
        }

        private void ChatForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormWidth"))
                    this.Width = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormWidth"]);
                if (Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormHeight"))
                    this.Height = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormHeight"]);

                if ((Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormPosX")) && (Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormPosY")))
                {
                    int x = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormPosX"]);
                    int y = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormPosY"]);
                    // ošetření vyskočení okna mimo obrazovku
                    if ((x >= Screen.PrimaryScreen.WorkingArea.Width - 5) || (x < 0 - this.Width + 5)) x = Screen.PrimaryScreen.WorkingArea.Width / 2;
                    if ((y >= Screen.PrimaryScreen.WorkingArea.Height - 5) || (y < 0 - this.Height + 5)) y = Screen.PrimaryScreen.WorkingArea.Height / 2;

                    this.Location = new Point(x, y);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("cannot set chatform properties");
            }
        }

        private void ChatForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (ChatTabPage tab in chatTabs.TabPages)
            {
                if (!CloseTab(tab))
                {
                    e.Cancel = true;
                    return;
                }
            }

            Global.ChangeISIMsettings("chatFormWidth", this.Width.ToString());
            Global.ChangeISIMsettings("chatFormHeight", this.Height.ToString());

            Global.ChangeISIMsettings("chatFormPosX", this.Location.X.ToString());
            Global.ChangeISIMsettings("chatFormPosY", this.Location.Y.ToString());
        }

        private void chatTabs_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Middle)
            {
                Point p = chatTabs.PointToClient(Cursor.Position);
                for (int i = 0; i < chatTabs.TabCount; i++)
                {
                    Rectangle r = chatTabs.GetTabRect(i);
                    if (r.Contains(p))
                    {
                        CloseTab(chatTabs.TabPages[i] as ChatTabPage);
                        break;
                    }
                }
            }
        }

        private int clickedTabIndex = -1;
        private void tabMenu_Opening(object sender, CancelEventArgs e)
        {
            addToConference.Text = Global.LangManager.Translate("addToConference");
            openProfile.Text = Global.LangManager.Translate("openProfile");
            chatHistory.Text = Global.LangManager.Translate("history");
            closeTab.Text = Global.LangManager.Translate("close");

            Point p = this.chatTabs.PointToClient(Cursor.Position);
            for (int i = 0; i < this.chatTabs.TabCount; i++)
            {
                Rectangle r = this.chatTabs.GetTabRect(i);
                if (r.Contains(p))
                {
                    clickedTabIndex = i;

                    ISIMContact contact = (chatTabs.TabPages[i] as ChatTabPage).contact;

                    bool callButtonVisible = contact.callStatus != CallStatus.callUnsupported;
                    /*if ((callButtonVisible) && (contact.callStatus == CallStatus.isLive))
                        callButtonVisible = Global.OpenForms.mainForm.skype.skypeLiveSession == (contact.contactObject as SkypeContact.ContactObject).conversation;*/
                    callContact.Visible = callButtonVisible;
                    if (callButtonVisible)
                    {
                        callContact.Text = contact.callStatus == CallStatus.none ? Global.LangManager.Translate("call") : Global.LangManager.Translate("endCall");

                        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChatForm));
                        if (contact.callStatus == CallStatus.none)
                            callContact.Image = ((System.Drawing.Image)(resources.GetObject("callContact.Image")));
                        else
                            callContact.Image = dropCallIcon;
                    }

                    chatHistory.Visible = File.Exists(Global.appDataFolder + "conversations" + Path.DirectorySeparatorChar + TextEdit.RemoveInvalidCharactersFromFileName(chatTabs.TabPages[i].Name) + ".txt");

                    openProfile.Visible = contact.protocol == "facebook";

                    addToConference.Visible = contact.callStatus != CallStatus.callUnsupported && chatTabs.SelectedTab != chatTabs.TabPages[i] && (chatTabs.SelectedTab as ChatTabPage).contact.callStatus != CallStatus.callUnsupported;

                    showVideo.Visible = contact.callStatus == CallStatus.isLive && Global.OpenForms.mainForm.skype.skypeLiveSession == (contact.contactObject as SkypeContact.ContactObject).conversation && contact.availability != Global.Availability.Conference;
                    Console.WriteLine(contact.callStatus.ToString() + contact.availability.ToString());
                    return;
                }
            }
            clickedTabIndex = -1;
            e.Cancel = true;
        }

        private void closeTab_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
                CloseTab(chatTabs.TabPages[clickedTabIndex] as ChatTabPage);
        }

        private void chatHistory_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            {
                string args = string.Format("/Select, {0}", Global.appDataFolder + "conversations" + Path.DirectorySeparatorChar + TextEdit.RemoveInvalidCharactersFromFileName(chatTabs.TabPages[clickedTabIndex].Name) + ".txt");

                System.Diagnostics.ProcessStartInfo pfi = new System.Diagnostics.ProcessStartInfo("explorer.exe", args);
                System.Diagnostics.Process.Start(pfi);
            }
        }

        private void callContact_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            {
                callContact.Enabled = false;
                ISIMContact contact = (chatTabs.TabPages[clickedTabIndex] as ChatTabPage).contact;
                if (contact.callStatus == CallStatus.none)
                    Global.ISIMFunctions.MakeCall(contact);
                else
                    Global.ISIMFunctions.EndCall(contact);
                callContact.Enabled = true;
            }
        }

        private void addToConference_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            {
                addToConference.Enabled = false;
                ISIMContact contact = (chatTabs.TabPages[clickedTabIndex] as ChatTabPage).contact;
                ISIMContact selectedContact = (chatTabs.SelectedTab as ChatTabPage).contact;
                Global.ISIMFunctions.AddToConference(selectedContact, contact);
                addToConference.Enabled = true;
            }
        }

        private void openProfile_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            { 
                ISIMContact contact = (chatTabs.TabPages[clickedTabIndex] as ChatTabPage).contact;
                if (contact.protocol == "facebook")
                {
                    string fbId = contact.id.Replace("@chat.facebook.com", "");
                    if (fbId.Substring(0, 1) == "-") fbId = fbId.Substring(1);
                    System.Diagnostics.Process.Start("http://www.facebook.com/" + fbId);
                }
            }
        }

        private void showVideo_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            {
                ISIMContact contact = (chatTabs.TabPages[clickedTabIndex] as ChatTabPage).contact;
                if ((contact.contactObject is SkypeContact.ContactObject) && (Global.OpenForms.mainForm.skype.skypeLiveSession == (contact.contactObject as SkypeContact.ContactObject).conversation))
                {
                    if (Global.OpenForms.videoRenderForm == null)
                        Global.OpenForms.videoRenderForm = new VideoRenderForm();
                    Global.OpenForms.videoRenderForm.Show();
                }
            }
        }

        private void ChatForm_Resize(object sender, EventArgs e)
        {
            if (lastState != WindowState)
            {
                lastState = WindowState;
                if (WindowState != FormWindowState.Minimized)
                    chatTabs_SelectedIndexChanged(null, null);
            }
        }

    }
}
